/*******************************************************************************
 * This file is part of blueprint4j www.blueprint4j.org.
 * 
 *     blueprint4j is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU Lesser General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 * 
 *     blueprint4j is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU Lesser General Public License for more details.
 * 
 *     You should have received a copy of the GNU Lesser General Public License
 *     along with blueprint4j. If not, see <http://www.gnu.org/licenses/>.
 ******************************************************************************/
package blueprint4j.comm;

import java.io.*;

import blueprint4j.utils.*;

public class StreamableInBase64 extends StreamableInNone {

	private String b_buffer = "";
	public StreamableInBase64() {}

	public byte[] readBuffer()
	throws IOException {
		byte[] buffer = super.readBuffer();
		if (buffer != null) {
			if (!(b_buffer.length() == 0 && buffer.length < 4 && ByteM.indexOf(buffer,"==".getBytes()) != -1)) {
				b_buffer += new String(buffer);
			}
		}
		if (b_buffer.length() > 4) {
			//buffer = new String(Base64.decode(b_buffer.toCharArray()));
			buffer = Base64.decode(b_buffer.substring(0,(b_buffer.length() / 4)*4).toCharArray());
			b_buffer = b_buffer.substring((b_buffer.length() / 4)*4);
			return buffer;
		}
		return null;
	}

	public void refresh() {
		if (b_buffer.length() < 4) b_buffer = "";
	}
	
	public void purge() {
		b_buffer = "";
	}

	public static void main(String args[]) throws Throwable {
		StreamableInNone stream = new StreamableInNone();
		StreamableInBase64 base = new StreamableInBase64();
		stream.setInStream(base);
		stream.setInStream(new ByteArrayInputStream("SGVsbG8gV29ybGQ=".getBytes()));
		Log.info.out(stream.readBuffer().toString());
	}
}


